<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	 public $layout='//layouts/column2';
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','contact','error','theLoai'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','delete','delete1','deleteMulti','duyet','huy','capNhat'), 
				'pbac'=>array('write'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','upload','admin','create'),
				'pbac'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);		
	}
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		$this->layout='//layouts/column1';
		$model=new Tintuc;
		$this->render('index', array('model'=>$model));
	}
	//View danh sach theo theo loai
	public function actionTheLoai($id)
	{
		$dataProvider = $dataProvider=new CActiveDataProvider('Tintuc', array(
                'criteria'=>array(
                        'condition'=>"loai_tin=".$id,
                        ),
				'pagination'=>array('pagesize'=>2),
                ));
		$this->render('theLoai',array(
			'dataProvider'=>$dataProvider,'id'=>$id
		));
	}
	
	public function actionView($id)
	{
		$model=new Tintuc;
		$post = Tintuc::model()->findByPk($id);
		$post->so_luong += 1;
		$post->save();
		$this->render('view',array(
			'model1'=>$this->loadModel($id), 'model'=>$model,
		));
	}
	
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionCreate()
	{
	
		$model=new Tintuc;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['Tintuc']))
		{
			$model->attributes=$_POST['Tintuc'];
			$model->ngay_dang = date('Y-m-d',strtotime($model->ngay_dang));	
			$model->hinh_anh = CUploadedFile::getInstance($model, 'hinh_anh');
			if(!empty($model->hinh_anh)){
				$name=time().date('Ymd')."_".$model->hinh_anh;
				$path = Yii::getPathOfAlias('webroot').'/images/tintuc/';   
				$model->hinh_anh->saveAs($path.$name);
				$model->hinh_anh=$name;
			}
			
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$oldImage=$model->hinh_anh;
		if(isset($_POST['Tintuc']))
		{
			$model->attributes=$_POST['Tintuc'];
			$model->ngay_dang = date('Y-m-d',strtotime($model->ngay_dang));	
			$model->hinh_anh = CUploadedFile::getInstance($model, 'hinh_anh');
			if($model->hinh_anh==null){
				$model->hinh_anh=$oldImage;
			}
			else{
				$name=time().date('Ymd')."_".$model->hinh_anh;
				$path = Yii::getPathOfAlias('webroot').'/images/tintuc/';   
				$model->hinh_anh->saveAs($path.$name);
				$model->hinh_anh=$name;
				if(is_file($path.$oldImage)){
					unlink($path.$oldImage);
				}
			}
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	//Xoa trong trang quan tri
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			$model=$this->loadModel($id);
			$path = Yii::getPathOfAlias('webroot').'/images/tintuc/'; 
			if(is_file($path.$model->hinh_anh)){
					unlink($path.$model->hinh_anh);
			}
			$model->delete();
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	//Xoa tren trang hien thi
	public function actionDelete1($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model=$this->loadModel($id);
			$path = Yii::getPathOfAlias('webroot').'/images/tintuc/'; 
			if(is_file($path.$model->hinh_anh)){
					unlink($path.$model->hinh_anh);
			}
			$model->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}
	public function actionAdmin()
	{
		$model=new Tintuc('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Tintuc']))
			$model->attributes=$_GET['Tintuc'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Tintuc::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	
	public function actionUpload()
	{
			Yii::import("ext.EAjaxUpload.qqFileUploader");
			$folder='tintuc/';// folder for uploaded files
			$allowedExtensions = array("jpg","jpeg","gif","png");//array("jpg","jpeg","gif","exe","mov" and etc...
			$sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
			$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
			$result = $uploader->handleUpload($folder);
			$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
			$fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
			$fileName=$result['filename'];//GETTING FILE NAME
	 
			echo $return;// it's array
	}
	
	public function actionCapNhat(){
		$act=$_GET['act'];
		$autoIdAll=$_POST['autoId'];
		if(count($autoIdAll)>0){
			foreach ($autoIdAll as $autoId){
				echo $autoId;
				if($act=='actDelete'){
					$model=$this->loadModel($autoId);
					$model->delete();
				}
				if($act=='actDuyet'){
					$model=$this->loadModel($autoId);
					$model->trang_thai=1;
					$model->save();
				}
				if($act=="actHuy"){
					$model=$this->loadModel($autoId);
					$model->trang_thai=0;
					$model->save();
				}
				
			}
		}
	}

}